package model.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import Hibernate.dao.Classroom;
import Hibernate.dao.ClassroomDAO;
import Hibernate.dao.Examiee;
import Hibernate.dao.ExamieeDAO;
import Hibernate.dao.Score;

public class ExamineeService {
	Map<String,String> map;
	ExamieeDAO examieeDao;
	String tempId;
	public static String basePath =ExamineeService.class.getClassLoader().getResource("/")
			.getPath().replace("WEB-INF/classes/", "");
	public void setExamieeDao(ExamieeDAO examieeDao) {
		this.examieeDao = examieeDao;
	}
	
	//获取临时考号
	public String getTempId(){
		tempId = "";
		ClassroomDAO classroomDao = new ClassroomDAO();
		Classroom tempClass = new Classroom();
		//classroom: 0为空，1为未满，2为满员
		if(classroomDao.findByStatus(1).size() != 0){
			tempClass = (Classroom) classroomDao.findByStatus(1).get(0);
			tempId = tempId + tempClass.getEpclassId() + "#";
			tempId = tempId + tempClass.getEpclassId() + "B";
			int nowNo = tempClass.getNowNo();
			int limitNo = tempClass.getLimitNo();
			nowNo = nowNo + 1;
			tempClass.setNowNo(nowNo);
			if(nowNo == limitNo){
				tempClass.setStatus(2);
			}
			tempId = tempId + nowNo;
			classroomDao.attachDirty(tempClass);
		}else if(classroomDao.findByStatus(0).size() != 0){
			tempClass = (Classroom) classroomDao.findByStatus(0).get(0);
			tempId = tempId + tempClass.getEpclassId() + "#";
			tempId = tempId + tempClass.getEpclassId();
			tempClass.setStatus(1);
			tempClass.setNowNo(1);
			tempId = tempId + 1;
			classroomDao.attachDirty(tempClass);
		}else {
			tempId = "-1#全部考场已满";
		}
		System.out.println(tempId);
		return tempId;
	}
	
	
	public String register(String userInfo){
		map = new HashMap<String,String>();
		System.out.println(userInfo);
		try{
			Examiee tempExamiee = new Examiee();
			JSONObject juserInfo = JSONObject.fromObject(userInfo);
			if(juserInfo.containsKey("userId")){
				tempExamiee.setUserId(juserInfo.getString("userId"));
				if(juserInfo.containsKey("idCardNum")){
					tempExamiee.setIdCardNum(juserInfo.getString("idCardNum"));
					if(juserInfo.containsKey("admitId")){
						tempExamiee.setAdmitId(juserInfo.getString("admitId"));
						if(juserInfo.containsKey("userName")){
							tempExamiee.setUserName(juserInfo.getString("userName"));
							if(juserInfo.containsKey("userDescribe")){
								tempExamiee.setUserDescribe(juserInfo.getString("userDescribe"));
								if(juserInfo.containsKey("phoneNum")){
									tempExamiee.setPhoneNum(juserInfo.getString("phoneNum"));
									if(juserInfo.containsKey("mail")){
										tempExamiee.setMail(juserInfo.getString("mail"));
										if(juserInfo.containsKey("subject")){
											tempExamiee.setSubject(juserInfo.getString("subject"));
											tempExamiee.setPsd("1234");
											tempExamiee.setState(0);
											if(juserInfo.containsKey("birthday")){
												tempExamiee.setBirthday(juserInfo.getString("birthday"));
												if(juserInfo.containsKey("policy")){
													tempExamiee.setPolicy(juserInfo.getString("policy"));
													if(juserInfo.containsKey("nation")){
														tempExamiee.setNation(juserInfo.getString("nation"));
														if(juserInfo.containsKey("eeid")){
															tempExamiee.setEeId(juserInfo.getString("eeid"));
															if(juserInfo.containsKey("gender")){
																tempExamiee.setGender(juserInfo.getString("gender"));
																if(getTempId().split("#")[1].equals("全部考场已满")){
																	map.put("flag", "false");
																	map.put("reason", tempId.split("#")[1]);
																}else{
																	tempExamiee.setClassroomId(tempId.split("#")[0]);
																	tempExamiee.setTempExamId(tempId.split("#")[1]);
																	if(examieeDao.findById(juserInfo.getString("userId")) != null){
																		map.put("flag", "false");
																		map.put("reason", "该数据已经存在");
																	}else{
																		tempExamiee.setUserPhoto("no picture");
																		examieeDao.save(tempExamiee);
																		map.put("flag", "true");
																	}
																}
															}else{
																map.put("flag", "false");
																map.put("reason", "性别不能为空");
															}
														}else{
															map.put("flag", "false");
															map.put("reason", "高考号不能为空");
														}
													}else{
														map.put("flag", "false");
														map.put("reason", "民族不能为空");
													}
												}else{
													map.put("flag", "false");
													map.put("reason", "政治面貌不能为空");
												}
											}else{
												map.put("flag", "false");
												map.put("reason", "生日不能为空");
											}
										}else{
											map.put("flag", "false");
											map.put("reason", "考试科目不能为空");
										}
									}else{
										map.put("flag", "false");
										map.put("reason", "电子邮箱不能为空");
									}
								}else{
									map.put("flag", "false");
									map.put("reason", "手机号码不能为空");
								}
							}else{
								map.put("flag", "false");
								map.put("reason", "自荐信息不能为空");
							}
						}else{
							map.put("flag", "false");
							map.put("reason", "考生名字不能为空");
						}
					}else{
						map.put("flag", "false");
						map.put("reason", "准考证号码不能为空");
					}
				}else{
					map.put("flag", "false");
					map.put("reason", "身份证号码不能为空");
				}
			}else{
				map.put("flag", "false");
				map.put("reason", "用户名不能为空");
			}
		}catch (JSONException e){
			map.put("flag", "false");
			//map.put("reason", "数据格式不正确");
			map.put("reason", e.getMessage());
		}
		
		return JSONObject.fromObject(map).toString();
	}
	
	public String confirm(String admitID){
		map = new HashMap<String,String>();
		try{
			JSONObject juserInfo = JSONObject.fromObject(admitID);
			if(juserInfo.containsKey("admitId")){
				List list =  examieeDao.findByAdmitId(juserInfo.getString("admitId"));
				if(list.size()==0){
					map.put("flag","false");
					map.put("reason", "没有找到数据");
				}else if(list.size()==1){
					if(getTempId().split("#")[1].equals("全部考场已满")){
						map.put("flag", "false");
						map.put("reason", tempId.split("#")[1]);
					}else{
						Examiee tempExamiee = (Examiee) list.get(0);
						tempExamiee.setClassroomId(tempId.split("#")[0]);
						tempExamiee.setTempExamId(tempId.split("#")[1]);
						examieeDao.attachDirty(tempExamiee);
						map.put("flag","true");
						map.put("tempExamId", tempId.split("#")[1]);
						map.put("classroomId", tempId.split("#")[0]);
					}
				}else{
					map.put("flag","false");
					map.put("reason", "服务器错误");
				}
			}else{
				map.put("flag","false");
				map.put("reason", "数据为空");
			}
		}catch (JSONException e){
			map.put("flag", "false");
			map.put("reason", "数据格式不正确");
		}
		return JSONObject.fromObject(map).toString();
	}
	
	public String examieeSearch(String admitID) {
		// TODO Auto-generated method stub
		map = new HashMap<String,String>();
		try{
			JSONObject juserInfo = JSONObject.fromObject(admitID);
			if(juserInfo.containsKey("admitId")){
				System.out.println("#"+juserInfo.getString("admitId"));
				List list =  examieeDao.findByAdmitId(juserInfo.getString("admitId"));
				if(list.size()==0){
					map.put("flag","false");
					map.put("reason", "没有找到数据");
				}else if(list.size()==1){
					Examiee tempExamiee = (Examiee) list.get(0);
					map.put("flag","true");
					map.put("userId",tempExamiee.getUserId());
					map.put("idCardNum",tempExamiee.getIdCardNum());
					map.put("admitId",tempExamiee.getAdmitId());
					map.put("userName", tempExamiee.getUserName());
					map.put("userPhoto", tempExamiee.getUserPhoto());
					map.put("phoneNum", tempExamiee.getPhoneNum());
					map.put("subject", tempExamiee.getSubject());
					map.put("eeid", tempExamiee.getEeId());
					map.put("gender", tempExamiee.getGender());
					map.put("tempExamId", tempExamiee.getTempExamId());
				}else{
					map.put("flag","false");
					map.put("reason", "服务器错误");
				}
			}else{
				map.put("flag","false");
				map.put("reason", "数据为空");
			}
		}catch (JSONException e){
			map.put("flag", "false");
			map.put("reason", "数据格式不正确");
		}
		return JSONObject.fromObject(map).toString();
	}
	
	
	//用于tablet，获取一个考场的学生姓名和考生Id的list
	public  String findExamieeByClassroom(String ClassroomInfo){
		// TODO Auto-generated method stub
		map = new HashMap<String,String>();
		try{
			JSONObject jclassInfo = JSONObject.fromObject(ClassroomInfo);	
			JSONArray examieeJson = new JSONArray();
			System.out.print(jclassInfo.toString());
			if(jclassInfo.containsKey("classroomId")){
				List list = examieeDao.findByClassroomId(jclassInfo.getString("classroomId"));
				if(list.size()==0){
					map.put("flag","false");
					map.put("reason", "没有找到数据");
					}else{
						for(int i=0;i<list.size();i++){
							System.out.print(i);
							Examiee tempExamiee = (Examiee) list.get(i);
							JSONObject jsonObject = JSONObject.fromObject(tempExamiee.toString());
							//jsonObject.put("admitId",tempExamiee.getAdmitId());
							//jsonObject.put("userName", tempExamiee.getUserName());
							examieeJson.add(jsonObject);
							map.put("flag","true");
							System.out.print(examieeJson.toString());
							map.put("data", examieeJson.toString());
						}
				}
			}else{
				map.put("flag", "false");
				map.put("reason", "数据为空请输入classroomId");
			}
		  }catch (JSONException e){
			map.put("flag", "false");
			map.put("reason", "数据格式不正确");
		  }
		return JSONObject.fromObject(map).toString();
		
	}
	

	
	public String examieeAll() {
		// TODO Auto-generated method stub
		map = new HashMap<String,String>();
		JSONArray examieeJson = new JSONArray();
		List list = examieeDao.findAll();
		for(int i=0;i<list.size();i++){
			Examiee tempExamiee = (Examiee) list.get(i);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("idCardNum",tempExamiee.getIdCardNum());
			jsonObject.put("admitId",tempExamiee.getAdmitId());
			jsonObject.put("userName", tempExamiee.getUserName());
			jsonObject.put("userPhoto", tempExamiee.getUserPhoto());
			jsonObject.put("phoneNum", tempExamiee.getPhoneNum());
			jsonObject.put("subject", tempExamiee.getSubject());
			jsonObject.put("eeid", tempExamiee.getEeId());
			jsonObject.put("gender", tempExamiee.getGender());
			jsonObject.put("tempExamId", tempExamiee.getTempExamId());
			examieeJson.add(jsonObject);
		}
		map.put("flag","true");
		map.put("data", examieeJson.toString());
		return JSONObject.fromObject(map).toString();
	}
	
	public InputStream examieeToExcel(String path, String userInfo){
		String[] examieeInfo = userInfo.split("#");
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("Users");
		List list = examieeDao.findAll();
		Object[][] value = new Object[list.size() + 1][examieeInfo.length];
		for (int m = 0; m < examieeInfo.length; m++) {
			value[0][m] = examieeInfo[m];
		}
		for (int i = 0; i < list.size(); i++) {
			Examiee users = (Examiee) list.get(i);
			ArrayList<String> arrayList = users.getInfo(examieeInfo);
			for (int j = 0; j < examieeInfo.length; j++) {
				value[i + 1][j] = arrayList.get(j);
			}
		}
		ExcelUtil.writeArrayToExcel(wb, sheet, list.size() + 1, examieeInfo.length,
				value);

		// ExcelUtil.writeWorkbook(wb, path);

		return getInputStream(wb, path);
	}
	public InputStream getInputStream(HSSFWorkbook wb, String path) {
		FileOutputStream fos = null;
		FileInputStream in = null;
		File f = new File(path);
		try {
			fos = new FileOutputStream(f);
			wb.write(fos);
			in = new FileInputStream(new File(path));
			wb.close();
			return in;
			// ByteArrayInputStream in = new ByteArrayInputStream( fos.)
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public String ExcelUpload(File file,String FileName)
	{
		map = new HashMap<String,String>();
		System.out.println(FileName);
			if(FileName==null||!FileName.endsWith(".xls"))
			{
				map.put("flag", "false");
				map.put("Info", "文件名为空 or 文件类型错误");
			}
			else if(file==null||!file.exists())
			{
				map.put("flag", "false");
				map.put("Info", "此文件不存在！");
			}else
			{
				return ExcelToExaminee(file);
			}
			return JSONObject.fromObject(map).toString();
	}
	
	public String ExcelToExaminee(File file) {
		map = new HashMap<String, String>();
		Map<String, String> value = new HashMap<String, String>();
		ArrayList<String> list = new ArrayList<String>();
		try {
			// 创建对Excel工作簿文件的引用
			HSSFWorkbook wookbook = new HSSFWorkbook(new FileInputStream(file));
			// 在Excel文档中，第一张工作表的缺省索引是0
			// 其语句为：HSSFSheet sheet = workbook.getSheetAt(0);
			HSSFSheet sheet = wookbook.getSheet("Users");
			// 获取到Excel文件中的所有行数
			int rows = sheet.getPhysicalNumberOfRows();
			// 遍历行
			for (int i = 0; i < rows; i++) {
				// 读取左上端单元格
				HSSFRow row = sheet.getRow(i);
				// 行不为空
				if (row != null) {
					// 获取到Excel文件中的所有的列
					int cells = row.getPhysicalNumberOfCells();
					// StringBuilder value = new StringBuilder();
					// StringBuilder info = new StringBuilder();
					// 遍历列
					for (int j = 0; j < cells; j++) {
						// 获取到列的值
						HSSFCell cell = row.getCell(j);
						if (cell != null) {
							switch (cell.getCellType()) {
							case HSSFCell.CELL_TYPE_FORMULA:
								break;
							case HSSFCell.CELL_TYPE_NUMERIC:
								if (i == 0)
									list.add(Double.toString(cell
											.getNumericCellValue()));
								else
									value.put(list.get(j), Double.toString(cell
											.getNumericCellValue()));
								break;
							case HSSFCell.CELL_TYPE_STRING:
								if (i == 0)
									list.add(cell.getStringCellValue().trim());
								else
									value.put(list.get(j), cell
											.getStringCellValue().trim());
								break;
							default:
								value.put(list.get(j), "");
								break;
							}
						}
					}
					if (i != 0) {
						for (int n = cells; n < list.size(); n++) {
							value.put(list.get(n), "");
						}
						Examiee examiee = new Examiee();
						examiee.setInfo(value);
						examieeDao.attachDirty(examiee);
					}
				}
			}
			wookbook.close();
			map.put("flag", "true");
			map.put("Info", "success");
		} catch (FileNotFoundException e) {
			map.put("flag", "false");
			map.put("Info", e.getMessage());
			// e.printStackTrace();
		} catch (IOException e) {
			map.put("flag", "false");
			map.put("Info", e.getMessage());
			// e.printStackTrace();
		}
		return JSONObject.fromObject(map).toString();

	}
	public String PhotoUpload(File file, String fileName, String userId) throws IOException {
		// TODO Auto-generated method stub
		map = new HashMap<String, String>();
		if (fileName==null||fileName.endsWith(".exe")) {
			map.put("flag", "flase");
			map.put("message", "不允许上传此类文件！");
		} else if(file==null||!file.exists()) {
			map.put("flag", "false");
			map.put("message", "此文件不存在！");
		} else {
			Examiee tempUser = examieeDao.findById(userId);
			if (tempUser == null) {
				map.put("flag", "false");
				map.put("message", "用户名不存在！");
			} else {
				FileInputStream fis = new FileInputStream(file);
//				System.out.println(basePath+ "userPhoto/");
				File outFile = new File(basePath+ "userPhoto/");
				if (!outFile.exists()) {
					outFile.mkdirs();
				}
				String path = basePath+ "userPhoto/" + userId + ".jpg";
				FileOutputStream fos = new FileOutputStream(new File(path));
				// System.out.println(outFile.getAbsolutePath());
				byte bt[] = new byte[500];
				while (fis.read(bt) > 0) {
					fos.write(bt);
				}
				fis.close();
				fos.flush();
				fos.close();
				tempUser.setUserPhoto("userPhoto/" + userId + ".jpg");
				examieeDao.attachDirty(tempUser);
				map.put("flag", "true");
				map.put("message", "上传成功");
			}
		}
		return JSONObject.fromObject(map).toString();
	}
}
